package com.zlq.javaWeb3.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(urlPatterns = "/uploadController")
@MultipartConfig(
        location = "D:\\tup"
)
public class UploadController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 可以用 request.getPart()方法获得名为 photo 的上传附件

        // 也可以用 request.getParts()获得所有上传附件（多文件上传）

        // 然后通过循环分别处理每一个上传的文件

        Part part = request.getPart("photo");

        if (part != null && part.getSubmittedFileName().length() > 0) {

            // 用 ServletContext 对象的 getRealPath()方法获得上传文件夹的绝对路径
            System.out.println("****************");

            String savePath = request.getServletContext().getRealPath("/src");

            // Servlet 3.1 规范中可以用 Part 对象的 getSubmittedFileName()方法获得上传的文件名

            // 更好的做法是为上传的文件进行重命名（避免同名文件的相互覆盖）

            part.write(savePath + "/" + part.getSubmittedFileName());

            request.setAttribute("hint", "成功!");

        } else {

            request.setAttribute("hint", "文件！！！");

        }

        // 跳转回到上传页面

        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

}


